package com.sm.util;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;

public class JTableUtil {
    // 设置表格内容居中显示
    public static void setTableColumnCenter(JTable table){
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, r);
    }

    // 设置表格隔行背景颜色不同
    public static void setbgcolor(JTable table){
        try {
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
                public java.awt.Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column){
                    if (row % 2 == 0) setBackground(new Color(223, 220, 239)); // 设置奇数行底色
                    else if (row % 2 == 1) setBackground(Color.white); // 设置偶数行底色
                    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                }
            };
            for (int i = 0; i < table.getColumnCount(); i++) {
                table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

